<?php if (!defined('BASEPATH'))exit('No direct script access allowed');
/**
 * 问答控制器
 */
class Wenda extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->assign("action", "wenda");
    }
    //问答首页
    function index() {
        
        $kw_arr = explode(",", $this->website_config['article_hot_key']);
        $search_word = $kw_arr[rand(0, count($kw_arr) - 1)];
        
        $query_params = "w.id,w.questioner_id,w.title,w.summary,w.readnum,w.answernum,w.focusnum,w.answer_id,w.answer_uid,i.head_img,i.nickname";
        $list = $this->db->query("select $query_params from tan_bbs_wenda w left join tan_users_info i on i.user_id = w.questioner_id where w.hot = 1 and w.status = 1 and w.is_show = 1 order by w.sort desc,w.id desc limit 15")->result_array();
        foreach ($list as $key=>$val){
            $answer = $this->db->query("select thumb,content,is_answer from tan_bbs_wenda_answer where wenda_id = $val[id] and is_show = 1 order by is_answer desc,likes desc limit 1")->row_array();
            if($answer){
                $answer['content'] = mb_strcut(strip_tags($answer['content']), 0, ($answer['thumb'] ? 120 : 150), "utf8")."...";
            }
            $list[$key]['answer'] = $answer;
            $list[$key]['summary'] = $val['summary']."...";
            $list[$key]['detail_url'] = site_url("wenda/".  encrypt_wenda_id($val['id']));
            $list[$key]['space_url'] = site_url("u/". encrypt_user_id($val['questioner_id']));
            $list[$key]['head_img'] = strstr($val['head_img'],"http") ? $val['head_img'] : $this->img_host.$val['head_img'];
        }
        $this->assign("search_word", $search_word);
        $this->assign("list", $list);
        $this->display('wenda/index.html');
    }

    //问答详情页
    function detial($wenda_id){
        $wenda_id = decrypt_wenda_id($wenda_id);
        $query_params = "w.id,w.title,w.questioner_id,w.content,w.summary,w.create_time,i.head_img,i.nickname";
        $item = $this->db->query("select $query_params from tan_bbs_wenda w left join tan_users_info i on i.user_id = w.questioner_id where w.id = $wenda_id and w.is_show = 1 and w.status = 1 order by w.id desc limit 1")->row_array();
        if(!$item){
            $this->display('deleted/index.html');exit;
        }
        $item['is_care'] = $this->user_id ? ($this->db->select("*")->from("bbs_wenda_care")->where(array("user_id"=>$this->user_id,"wenda_id"=>$wenda_id,"is_del"=>1))->order_by("id")->get()->num_rows() ? 1 : 0) : 0;
        $this->db->select("*")->from("bbs_wenda_answer")->where(array("user_id"=>$this->user_id,"wenda_id"=>$wenda_id))->order_by("id")->get()->num_rows();
        $item['is_self'] = $this->user_id == $item['questioner_id'];
        $item['wenda_id'] = encrypt_wenda_id($wenda_id);
        $item['is_answer'] = $this->user_id ? ($this->db->select("*")->from("bbs_wenda_answer")->where(array("user_id"=>$this->user_id,"wenda_id"=>$wenda_id))->order_by("id")->get()->num_rows() ? 1 : 0) : 0;
        $item['content'] = str_replace("div", "p", $item['content']);
        $item['title_s'] = mb_strcut($item['title'], 0, 30, "utf8")."...";
        $item['summary_s'] = strip_tags($item['summary']);
        $item['detail_url'] = site_url("wenda/".  encrypt_wenda_id($wenda_id));
        $item['space_url'] = site_url("u/".encrypt_user_id($item['questioner_id']));
        $item['questioner_uid'] = encrypt_user_id($item['questioner_id']);
        $item['head_img'] = strstr($item['head_img'],"http") ? $item['head_img'] : $this->img_host.$item['head_img'];
        $item['create_time'] = $this->set_time_three($item['create_time']);
        $item['answer_add_url'] = site_url("wenda_answer_add/".  encrypt_wenda_id($wenda_id));
        $this->assign("site_title", $item['title']);
        $this->assign("item", $item);
        $this->display('wenda/detial.html');
    }
    
    //回答详情页
    function answer($wenda_id,$answer_id){
        $wenda_id = decrypt_wenda_id($wenda_id);
        $answer_id = decrypt_answer_id($answer_id);
        //判断是否存在该答案
        $query_params = "a.*,i.head_img,i.nickname,w.title";
        $item = $this->db->query("select $query_params from tan_bbs_wenda_answer a left join tan_users_info i on i.user_id = a.user_id left join tan_bbs_wenda w on w.id = a.wenda_id where a.id = $answer_id and a.wenda_id = $wenda_id and a.is_show = 1 order by a.id desc limit 1")->row_array();
        if(!$item){
            $this->display('deleted/index.html');exit;
        }
        
        $this->assign("title", $item['title']);
        
        $repeat_str = array("<br>",'<p><span style="font-size: 13.3333px;"></span></p>',"<p><br></p>","<p>&nbsp;</p>",'<p><span style="color: rgb(51, 51, 51);">&nbsp;</span></p>','<p><span style="color: rgb(62, 62, 62);">&nbsp;</span></p>','<p><strong><span style="font-size: 10.5pt; color: black;">&nbsp;</span></strong></p>','<p><span style="font-size: 10.5pt; color: black;">&nbsp;</span></p>');
        $item['content'] = str_replace($repeat_str, "", $item['content']);
        $item['content_'] = strip_tags($item['content']);
        $item['title_'] = $item['title'];
        $item['title'] = mb_strcut($item['title'], 0, 30, "utf8")."...";
        $item['is_self'] = $this->user_id == $item['user_id'] ? 1 : 0;
        $item['is_care'] = $this->user_id ? ($this->db->select("*")->from("bbs_fans")->where(array("followuid"=>$this->user_id,"user_id"=>$item['user_id'],"is_del"=>1))->order_by("id")->get()->num_rows() ? 1 : 0) : 0;
        $item['is_like'] = $this->user_id ?($this->db->select("*")->from("bbs_wenda_answer_like")->where(array("user_id"=>$this->user_id,"answer_id"=>$answer_id,"is_del"=>1))->order_by("id")->get()->num_rows() ? 1 : 0) : 0;
        $item['answer_id'] = encrypt_answer_id($answer_id);
        $item['answer_uid'] = encrypt_user_id($item['user_id']);
        $item['space_url'] = site_url("u/".encrypt_user_id($item['user_id']));
        $item['wenda_url'] = site_url("wenda/". encrypt_wenda_id($wenda_id));
        $item['detail_url'] = site_url("wenda/".  encrypt_wenda_id($wenda_id)."/answer/".  encrypt_answer_id($answer_id));
        $item['edit_url'] = site_url("wenda_answer_edit/".encrypt_answer_id($answer_id));
        $item['head_img'] = strstr($item['head_img'],"http") ? $item['head_img'] : $this->img_host.$item['head_img'];
        $item['create_time'] = $this->set_time_three($item['create_time']);
        $this->assign("item", $item);
        $this->assign("site_title", $item['title_']);
        $this->display("wenda/answer.html");
    }
     //问答搜索页面
    function search(){
        $kw = trim($_REQUEST['kw']);
        $kw_arr = explode(",", $this->website_config['wenda_hot_key']);
        $this->assign("kw_arr", $kw_arr);
        $this->assign("keyword", $kw);
        $this->display("wenda/search.html");
    }
    
    //问题查询结果页面
    function search_result(){
        $kw = trim($_REQUEST['kw']);
        $query_params = "w.id,w.title,w.questioner_id,w.readnum,w.answernum,w.create_time,w.focusnum,i.head_img,i.nickname";
        $list = $this->db->query("select $query_params from tan_bbs_wenda w left join tan_users_info i on i.user_id = w.questioner_id where w.title like '%$kw%' and w.status = 1 and w.is_show = 1 order by w.hot desc,w.sort desc limit 15")->result_array();
        foreach ($list as $key=>$val){
            $list[$key]['detail_url'] = site_url("wenda/".  encrypt_wenda_id($val['id']));
            $list[$key]['space_url'] = site_url("u/". encrypt_user_id($val['questioner_id']));
            $list[$key]['create_time'] = $this->set_time_three($val['create_time']);
            $list[$key]['head_img'] = strstr($val['head_img'],"http") ? $val['head_img'] : $this->img_host.$val['head_img'];
            $list[$key]['title'] = str_replace($kw, "<span class='col-red'>$kw</span>", $val['title']);
        }
        $this->assign("list", $list);
        $this->assign("keyword", $kw);
        $this->display('wenda/search_result.html');
    }
    //提问界面
    function asking(){
        $this->is_login();
        $mobile = $this->db->query("select mobile from tan_users where user_id = ".$this->user_id." order by user_id limit 1")->row_array();
        $this->assign("is_mobile", $mobile['mobile'] ? 1 : 0);
        $this->assign("title", $this->session->userdata('wenda_title'));
        $this->assign("content", $this->session->userdata('wenda_content'));
        $this->display('wenda/asking.html');
    }
    
    //提问-第一步
    function asking_next(){
        $this->is_login();
        if($_POST){
            $title = isset($_POST['title']) ? trim($_POST['title']) : "";
            $content = isset($_POST['content']) ? trim($_POST['content']) : "";
            if(!$title){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "问答标题不能为空哦";
                echo JSON($mess);exit;
            }
            
            $allergicWord = file_get_contents("http://static.tan66.com/upfiles/files/badwords.txt");
            $allergicWord = str_replace(array("\r\n", "\r", "\n"),'',$allergicWord);
            $allergicWord= explode('|',$allergicWord);
            $info=0;
            $tinfo=0;
            for ($i=0;$i<count($allergicWord);$i++){  
                $check = substr_count($content, $allergicWord[$i]);
                $tcheck = substr_count($title,$allergicWord[$i]);
                if($check>0){
                    $info = $check;
                    break;
                }
                if($tcheck>0){
                    $tinfo = $tcheck;
                    break;;
                }
            }  
            if($info>0 || $tcheck>0){
                $errmes['reqStatus'] = false;
                $errmes['errorMsg'] = "标题或内容里面有非法或敏感内容，请修正哦";
                echo JSON($errmes);exit;
            }
            
            $this->session->set_userdata("wenda_title",$title);
            $this->session->set_userdata("wenda_content",$content);
            
            $mess['reqStatus'] = true;
            $mess['url'] = site_url("wenda/asking_complete");
            echo JSON($mess);exit;
        }
    }
    //保存标签
    function asking_tags(){
        $this->is_login();
        if($_POST){
            $tags = isset($_POST['tags']) ? trim($_POST['tags']) : "";
            $arr_ = array();
            if($tags){
                $tag_arr = explode(",", $tags);
                foreach ($tag_arr as $key=>$val){
                    $temp = array();
                    $tag = explode("_", $val);
                    $temp['id'] = $tag[1];
                    $temp['name'] = $tag[0];
                    $arr_[] = $temp;
                }
                $this->session->set_userdata("wenda_tags",serialize($arr_));
            }
            
            $mess['reqStatus'] = true;
            $mess['url'] = site_url("wenda/asking");
            echo JSON($mess);exit;
        }
    }
    //提问-最后一步
    function asking_complete(){
        $this->is_login();
        if($_POST){
            $title = $this->session->userdata('wenda_title');
            $content = $this->session->userdata('wenda_content');
            $tags = isset($_POST['tags']) ? trim($_POST['tags']) : "";
            if(!$title){
                $errmes['reqStatus'] = false;
                $errmes['errorMsg'] = "问答标题不能为空哦";
                echo JSON($errmes);exit;
            }
            
            $summary = mb_strcut(strip_tags(trim(str_replace("&nbsp;", "", $content))),0,300);
            $data = array();
            $data['questioner_id'] = $this->user_id;
            $data['title'] = $title;
            $data['content'] = strip_tags($content, "<br><img><p><div><a>");
            $data['summary'] = $summary;
            $data['thumb'] = "";
            $data['tags_name'] = $tags;
            $data['create_time'] = time();
            $data['status'] = 1;
            $data['month'] = date("Ym");
            $data['day'] = date("Ymd");
             $this->db->trans_begin();//开启事务
            
            $this->db->insert("bbs_wenda", $data);
            $insert_id = $this->db->insert_id();
            $query1 = $this->db->query("update tan_bbs_count set question_count = question_count + 1 where user_id = ".$this->user_id);
            //更新文章标签统计
            $tags ? $query2 = $this->update_tags($tags) : $query2 = 1;
            if($insert_id && $query1 && $query2){
                $this->db->trans_commit();//提交事务
                
                $this->db->insert("bbs_notice",array('user_id'=>$this->user_id,'operator_id'=>$insert_id,"event_type"=>'event_add_wenda',"type"=>"wenda","is_show"=>1,"create_time"=>time()));
                //发送消息
                $followers = $this->db->select("followuid")->from("bbs_fans")->where(array("user_id"=>user_id,"is_del"=>1))->order_by("id desc")->get()->result_array();
                if($followers){
                    $datas = array();
                    foreach ($followers as $key=>$val){
                        $data = array();
                        $data['user_id'] = 0;
                        $data['recieve_id'] = $val['followuid'];
                        $data['operator_id'] = $insert_id;
                        $data['event_type'] = "event_add_wenda_care";
                        $data['create_time'] = time();
                        $data['is_show'] = 1;
                        $data['type'] = "wenda";
                        $datas[] = $data;
                    }
                    $datas[] = array('user_id'=>0,'recieve_id'=>$this->user_id,'operator_id'=>$insert_id,"event_type"=>'event_comment_wenda',"type"=>"wenda","is_show"=>1,"create_time"=>time());
                    $this->db->insert_batch("bbs_notice",$datas);
                }
                
                $this->session->set_userdata("wenda_title","");
                $this->session->set_userdata("wenda_content","");
                $this->session->set_userdata("wenda_tags","");
                
                $mess['reqStatus'] = true;
                $mess['url'] = site_url("/wenda/".encrypt_wenda_id($insert_id));
                $mess['errorMsg'] = "发布成功，请耐心等待伙伴们的解答哦";
                echo JSON($mess);exit;
            }else{
                $this->db->trans_rollback();//事务回滚
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "发布失败，请稍后重试";
                echo JSON($mess);exit;
            }
            
        }
        $tags = $this->session->userdata('wenda_tags');
        if(!$tags){
            $tags = $this->db->select("id,name")->from("bbs_wenda_tags")->where(array("is_recommend"=>1))->order_by("sort desc")->get()->result_array();
            $this->assign("is_recommend",1);
        }else{
            $tags = unserialize($tags);
        }
        
        $this->assign("tags", $tags);
        $this->display("wenda/asking_complete.html");
    }
    
    //清空问答
    function asking_cancel(){
        if($_POST){
            $this->session->set_userdata("wenda_title","");
            $this->session->set_userdata("wenda_content","");
            $this->session->set_userdata("wenda_tags","");
            $mess['reqStatus'] = true;
            echo JSON($mess);exit;
        }
    }
    
    //答案编辑
    function answer_add($wenda_id){
        $this->is_login();
        $wenda_id = decrypt_wenda_id($wenda_id);
        $item = $this->db->query("select w.* from tan_bbs_wenda w where w.id = $wenda_id order by w.id desc limit 1")->row_array();
        $item['wenda_id'] = encrypt_wenda_id($item['id']);
        $item['wenda_url'] = site_url("wenda/".  encrypt_wenda_id($wenda_id));
        $this->assign("item", $item);
        $this->display("wenda/answer_add.html");
    }
    
    //答案编辑
    function answer_edit($answer_id){
        $this->is_login();
        $answer_id = decrypt_answer_id($answer_id);
        $item = $this->db->query("select a.*,w.title from tan_bbs_wenda_answer a left join tan_bbs_wenda w on w.id = a.wenda_id where a.id = $answer_id and a.is_show = 1 order by a.id desc limit 1")->row_array();
        $item['answer_url'] = site_url("wenda/".encrypt_wenda_id($item['wenda_id'])."/answer/".encrypt_answer_id($answer_id));
        $item['answer_id'] = encrypt_answer_id($answer_id);
        $item['wenda_id'] = encrypt_wenda_id($item['wenda_id']);
        $item['answer_uid'] = encrypt_user_id($item['user_id']);
        
        $this->assign("item", $item);
        $this->display("wenda/answer_edit.html");
    }

    //是否登录
    private function is_login(){
        if($_POST && !$this->user_id){
            $mess['reqStatus'] = false;
            $mess['errorMsg'] = "请先登录，再操作哦";
            echo JSON($mess);exit;
        }
        
        if(!$this->user_id){
            $url = site_url("account/login").$this->get_next_request_url();
            header("Location:".$url);
            exit;
        }
    }
    //更新文章标签统计
    private function update_tags($tags){
        $flag = 1;
        $tag_arr = explode(",", $tags);
        foreach ($tag_arr as $key=>$val){
            $tag = explode("_", $val);
            
            $sql = "UPDATE tan_bbs_wenda_tags SET use_count = use_count + 1 WHERE id = $tag[1];";
            $flag = $this->db->query($sql);
            if(!$flag){
                break;
            }
        }
        return $flag;
    }
}
